package gov.child.dao.impl;

import gov.child.dao.AbstractDao;
import gov.child.dao.ComplaintDao;
import gov.child.dao.exception.*;
import gov.child.entities.po.EComplaint;
import gov.child.entities.vo.Page;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * The type Complaint dao. --finish
 *
 * @author fzh
 * @since 2017 /9/10
 */
@Repository("complaintDao")
public class ComplaintDaoImpl extends AbstractDao implements ComplaintDao {

    @Override
    public EComplaint findById(Integer id) throws EntityQueryException {
        Session session = currentSession();
        return (EComplaint) session.createQuery("from EComplaint where id = :id order by createTime")
                .setParameter("id", id).getSingleResult();
    }

    @Override
    public List findAll(Page page) {
        Session session = currentSession();
        Query query = session.createQuery("from EComplaint order by createTime");
        return doPaginate(query, page);
    }

    @Override
    public List findByGuideId(Integer guideId, Page page) throws EntityQueryException {
        Session session = currentSession();
        String hql = "from EComplaint c where c.guideId = :gid order by createTime";
        Query query = session.createQuery(hql).setParameter("gid", guideId);
        return doPaginate(query, page);
    }

    @Override
    public List findByUserId(Integer userId, Page page) throws EntityQueryException {
        Session session = currentSession();
        String hql = "from EComplaint c where c.userId = :uid order by createTime";
        Query query = session.createQuery(hql).setParameter("uid", userId);
        return doPaginate(query, page);
    }

    @Override
    public void save(EComplaint complaint) throws EntitySaveException {
        currentSession().save(complaint);
    }

    @Override
    public void delete(EComplaint complaint) throws EntityDeleteException {
        currentSession().delete(complaint);
    }

    @Override
    public void update(EComplaint complaint) throws EntityUpdateException {
        // TODO maybe need optimization
        currentSession().update(complaint);
    }

    @Override
    public Long total() throws PageInitialException {
        Session session = currentSession();
        String hql = "select count(*) from EComplaint";
        return (Long) session.createQuery(hql).uniqueResult();
    }
}
